package demo.practice.leetcode_msjd;

public class Msjd0205 {

    public static void main(String[] args) {
        ListNode l1=new ListNode(2);
        l1.next= new ListNode(4);
        l1.next.next= new ListNode(3);


        ListNode l2=new ListNode(5);
        l2.next= new ListNode(6);
        l2.next.next= new ListNode(4);


        Msjd0205 msjd0205= new Msjd0205();
        msjd0205.addTwoNumbers(l1,l2);
    }


    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode n1 = l1;
        ListNode n2 = l2;
        int jw = 0;//进位

        ListNode head = null;
        ListNode current = null;


        while (n1 != null && n2 != null) {
            int add = n1.val + n2.val+jw;
            if (head == null) {
                head = new ListNode(add % 10);
                current = head;
            } else {
                current.next = new ListNode(add % 10);
                current=current.next;
            }
            jw = add / 10;
            n1=n1.next;
            n2=n2.next;
        }

        ListNode rest= n1==null? n2:n1;
        while(rest!=null){
            int add=rest.val+jw;
            current.next= new ListNode(add % 10);
            current=current.next;
            rest=rest.next;
            jw = add / 10;
        }

        if(jw!=0)
            current.next= new ListNode(jw);
        return head;
    }


    public int addTwoNumbers2(ListNode l1, ListNode l2) {
        return sumLink(l1) + sumLink(l2);
    }

    private int sumLink(ListNode l1) {
        if (l1 == null)
            return 0;
        int mi1 = 0;
        int sum1 = 0;
        ListNode node = l1;
        while (node != null) {
            int add = node.val;
            for (int i = 0; i < mi1; i++) {
                add = add * 10;
            }
            sum1 += add;
            mi1++;
            node = node.next;
        }
        return sum1;
    }
}
